<template>
  <div class="city-search">
    <div class="search">
      <input
        type="text"
        placeholder="输入城市名字或拼音"
        class="search-input"
        v-model="keyWord"
      >
    </div>
    <div class="search-content" ref="wrapper"  v-show="keyWord">
      <ul class="search-content-list">
        <li
        class="search-item"
        border-bottom-1px
        v-for="item of list"
        :key="item.id"
        @click="handleChangeCity(item.name)"
        >
          {{item.name}}
        </li>
        <li class="search-item" border-bottom-1px v-show="hasNoData">没有找到匹配项</li>
      </ul>
    </div>
</div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapActions} from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: {
      type: Object
    }
  },
  data () {
    return {
      keyWord: '',
      timer: null,
      list: []
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  methods: {
    handleChangeCity (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapActions({
      changeCity: 'changeCity'
    })
  },
  watch: {
    keyWord () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].map((item) => {
            if (item.spell.indexOf(this.keyWord) > -1 || item.name.indexOf(this.keyWord) > -1) {
              result.push(item)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper, {click: true})
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/variable.styl'
  .city-search
    height 100%
    .search
      height 74px
      background-color $bgColor
      padding 10px
      box-sizing border-box
      .search-input
        width 100%
        height 100%
        font-size 24px
        color #333
        background-color #fff
        text-align center
        border none
        border-radius 4px
        padding 0 10px
        box-sizing border-box
    .search-content
      position fixed
      top 160px
      left 0
      bottom 0
      right 0
      background-color #f5f5f5
      overflow hidden
      z-index 10
      .search-item
        line-height 60px
        font-size 20px
        background-color #fff
        text-indent 20px
        cursor pointer
</style>
